<!-- 用户组页面 -->
<template>
  <div class="crowd-management-container">
    <!-- 顶部标题和新建按钮 -->
    <div class="header">
      <span class="title">信息管理</span>
      <el-button type="primary" class="add-button" @click="beforeAddCrowd">新建人群</el-button>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true">
        <el-form-item label="人群名称">
          <el-input placeholder="请输入人群名称" v-model="searchForm.groupName"></el-input>
        </el-form-item>
        <!--        <el-form-item label="启动状态">-->
        <!--          <el-select placeholder="请选择状态" v-model="searchForm.status">-->
        <!--            <el-option label="全部" value=""></el-option>-->
        <!--            <el-option label="已启动" value="1"></el-option>-->
        <!--            <el-option label="未启动" value="0"></el-option>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item label="更新时间">
          <el-date-picker
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
              v-model="searchForm.timeRange"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="loadCrowdList">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 人群表格 -->
    <el-card class="table-card">
      <el-table :data="crowdList" border stripe>
        <el-table-column prop="id" label="编号" width="150" align="center"></el-table-column>
        <el-table-column prop="groupName" label="人群名称" width="150" align="center"></el-table-column>
        <el-table-column label="用户类型" width="150" align="center">
          <template #default="scope">
            <el-button type="text" @click="viewUserTypes(scope.row)">查看({{scope.row.tagIdsList.length}})</el-button>
          </template>
        </el-table-column>
        <el-table-column label="活动数量" width="150" align="center">
          <template #default="scope">
            <el-button type="text" @click="viewActivities(scope.row)">查看({{scope.row.activityCount}})</el-button>
          </template>
        </el-table-column>
        <el-table-column label="描述" align="center">
          <!-- 使用插槽自定义内容，为空时显示默认文本 -->
          <template #default="scope">
            {{ scope.row.description || '这是一个人群描述' }}
          </template>
        </el-table-column>
        <el-table-column prop="createAt" label="创建时间" width="180" align="center"></el-table-column>
        <!--        <el-table-column prop="status" label="状态" width="180">-->
        <!--          <template #default="scope">-->
        <!--            <el-switch-->
        <!--                v-model="scope.row.status"-->
        <!--                active-value="active"-->
        <!--                inactive-value="inactive"-->
        <!--            />-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="操作" width="150" align="center">
          <template #default="scope">
            <el-button type="text" @click="editCrowd(scope.row)">编辑</el-button>
            <el-button type="text" @click="deleteCrowd(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
          class="pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
      </el-pagination>
    </el-card>

    <!-- 新建/编辑人群对话框 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="50%"
        :before-close="handleClose"
    >
      <el-form :model="crowdForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="人群名称" required>
              <el-input v-model="crowdForm.groupName" placeholder="请输入人群名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!--            <el-form-item label="启动状态">
                          <el-switch
                              v-model="crowdForm.status"
                              active-value="1"
                              inactive-value="0"
                              active-text="已启动"
                              inactive-text="未启动">
                          </el-switch>
                        </el-form-item>-->
          </el-col>
        </el-row>
        <!--        <el-form-item label="描述">
                  <el-input
                      type="textarea"
                      :rows="3"
                      v-model="crowdForm.description"
                      placeholder="请输入人群描述介绍">
                  </el-input>
                </el-form-item>-->
        <!-- 新增：人群特征标签选择（穿梭框形式） -->
        <el-form-item label="用户类型">
          <el-transfer
              v-model="selectedTagKeys"
              :data="tagOptions"
              :titles="['可选标签', '已选标签']"
              :filterable="true"
              filter-placeholder="搜索标签"
              :width="['35%', '35%']"
              @change="handleTagChange"
          ></el-transfer>
        </el-form-item>
        <el-form-item label="用户数">
          <el-input v-model="crowdForm.userNumber" placeholder="请输入预估人数" disabled></el-input>
        </el-form-item>
        <el-form-item label="商家id">
          <el-input v-model="crowdForm.businessId" placeholder="请输入预估人数"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="saveCrowd">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, nextTick, onMounted} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from "axios";

onMounted(()=>{
  loadCrowdList();
  loadTagsList();
})
// 人群列表数据
const crowdList = ref([])

// 搜索表单 status: ''
const searchForm = ref({
  groupName: '',
  status: '',
  timeRange: []// 时间范围
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 50
})

// 人群表单
const crowdForm = reactive({
  id: null,
  groupName: '',
  userTypes: [],
  userNumber: 0,
  //userTypeCount: 0,
  activityCount: 5,
  description: '人群描述介绍',
  status: '1',
  businessId:0//此商家管理员对应的商家
})

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('新建人群')
//const isEdit = ref(false)

// 用户类型相关
const inputVisible = ref(false)
const inputValue = ref('')
const typeInput = ref(null)

// 加载人群列表
const loadCrowdList = () => {
  // 构建查询参数
  const params = {
    pageNo: pagination.currentPage,
    pageSize: pagination.pageSize,
    groupName: searchForm.value.groupName,
    startTime: searchForm.value.timeRange?.[0] || null,
    endTime: searchForm.value.timeRange?.[1] || null
  }
  console.log('加载人群列表参数:', params)
  axios.post(BASE_URL + '7070/admin/basic/userGroup/list', params).then((response) => {
    console.log('人群列表响应:', response.data)
    if (response.data.code === '0') {
      ElMessage.success('加载人群列表成功')
      crowdList.value = (response.data.data.objects || []).map(item => ({
        ...item, // 保留原有字段
        // 新增 tagIdsList 字段，存储转换后的数字数组
        tagIdsList: item.tagIds
            ? item.tagIds.split(',').map(Number) // 非空时分割并转数字
            : [] // 空值时返回空数组
      }));
      console.log('crowdList.value:', crowdList.value[0].tagIdsList)
      pagination.total = response.data.data.total || 0;
    }else {
      ElMessage.error('加载人群列表失败: ' + (response.data.msg || '未知错误'))
    }
  }).catch(error => {
    console.error('加载人群列表异常:', error)
    if (error.message.includes('CORS')) {
      ElMessage.error('跨域请求被阻止，请检查后端CORS配置');
    }/* else if (error.message.includes('401')) {
      ElMessage.error('请先登录');
    }*/
    else if (error.message.includes('404')) {
      ElMessage.error('请求的接口不存在');
    } else {
      ElMessage.error('网络错误，加载人群列表失败');
    }
  })
}

// 重置搜索
const resetSearch = () => {
  searchForm.value.groupName = '';
  searchForm.value.status = '';
  searchForm.value.timeRange = [];
  pagination.currentPage = 1;
  loadCrowdList();
  ElMessage.success('搜索条件已重置')
}
// 分页变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  loadCrowdList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  loadCrowdList()
}

// 准备添加人群
const beforeAddCrowd = () => {
  dialogTitle.value = '新建人群'
  //isEdit.value = false
  Object.assign(crowdForm, {
    id: null,
    groupName: '',
    userTypes: [],
    userTypeCount: 0,
    activityCount: 5,
    description: '人群描述介绍',
    status: '1'
  })
  // 重置选中的标签ID
  selectedTagKeys.value = [];
  // 加载所有标签
  loadTagsList();
  // 打开弹窗
  dialogVisible.value = true
}

// 编辑人群
const editCrowd = (row) => {
  dialogTitle.value = '编辑人群'
  //isEdit.value = true
  Object.assign(crowdForm, JSON.parse(JSON.stringify(row)))
  dialogVisible.value = true
}

// 删除人群
const deleteCrowd = (id) => {
  if(id==null){
    ElMessage.error('请重新选择要删除的店铺!');
    return;
  }
  if(confirm('您确认要删除本店铺吗?')){
    console.log("删除的参数"+id)
    axios.get(BASE_URL+'7070/admin/basic/userGroup/delete?id='+id).then((response)=>{
      if(response.data.code==0){
        ElMessage.success('删除成功!');
        loadCrowdList();
      }else{
        ElMessage.error(response.data.msg);
      }
    })
  }
}

// 查看用户类型 - 从tagOptions中查找标签名
const viewUserTypes = (row) => {
  if (!row.tagIdsList || row.tagIdsList.length === 0) {
    ElMessage.info(`人群 ${row.groupName} 没有设置用户类型`);
    return;
  }
  // 从tagOptions中查找对应的标签名称
  const typeNames = row.tagIdsList.map(tagId => {
    // 在tagOptions中查找key等于tagId的标签
    const tag = tagOptions.value.find(option => option.key === tagId);
    // 如果找到返回标签名，否则返回未知标签
    return tag ? tag.label : `未知标签(${tagId})`;
  });
  ElMessage.info(`人群 ${row.groupName} 的用户类型: ${typeNames}`);
}
// 查看活动
const viewActivities = (row) => {
  ElMessage.info(`正在查看人群 ${row.groupName} 的活动`)
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 保存人群
const saveCrowd = () => {
  if (!crowdForm.groupName) {
    ElMessage.warning('请填写人群名称')
    return
  }
  // 构建提交数据（根据后端要求调整格式）
  const submitData = {
    ...crowdForm,
    businessId: (crowdForm.businessId) || 0, // 转为数字，默认为0
    tagIds: crowdForm.userTypes.length > 0 ? crowdForm.userTypes.join(',') : null
  };
  console.log('提交数据:', submitData);
   // 调用保存接口
    axios.post(BASE_URL + '7070/admin/basic/userGroup/save', submitData)
        .then(response => {
          console.log('保存响应:', response.data);
          if (response.data.code === '0') {
            loadCrowdList(); // 重新加载列表
            dialogVisible.value = false;
            ElMessage.success('保存成功')
          } else {
            ElMessage.error('保存失败: ' + response.data.msg);
          }
        });
  // if (isEdit.value) {
  //   // 更新人群
  //   const index = crowdList.value.findIndex(crowd => crowd.id === crowdForm.id)
  //   if (index !== -1) {
  //     crowdList.value[index] = {
  //       ...crowdForm,
  //       userTypeCount: crowdForm.userTypes.length
  //     }
  //   }
  //   ElMessage.success('更新成功')
  // } else {
  //   // 添加人群
  //   const newId = Math.max(...crowdList.value.map(crowd => crowd.id)) + 1
  //   crowdList.value.unshift({
  //     ...crowdForm,
  //     id: newId,
  //     userTypeCount: crowdForm.userTypes.length,
  //     createTime: new Date().toLocaleString()
  //   })
  //   ElMessage.success('添加成功')
  // }
  dialogVisible.value = false
}
// 所有可选标签（从接口获取）
const tagOptions = ref([]);
// 已选中的标签ID（双向绑定到el-transfer）
const selectedTagKeys = ref([]);
// 加载所有用户标签（从标签表获取）
const loadTagsList = () => {
  // 调用后端获取标签表的接口（请替换为实际接口地址）
  axios.get(BASE_URL + '3030/basic/tagLibrary/info/userTagsChoose')
      .then((response) => {
        console.log('标签列表响应:', response.data.data);
        if (response.data.code === '0') {
          // 格式化标签数据为el-transfer需要的格式：{ key: 标签ID, label: 标签名称 }
          tagOptions.value = response.data.data.map(tag => ({
            key: tag.tagLibraryBO.id, // 标签唯一标识（用于选中状态）
            label: tag.tagLibraryBO.tagName // 标签显示名称
          }));
          console.log('加载所有标签成功:', tagOptions.value);
        } else {
          ElMessage.error('加载标签失败: ' + (response.data.msg || '未知错误'));
        }
      })
      .catch(error => {
        console.error('加载标签接口异常:', error);
        ElMessage.error('网络错误，无法加载标签');
      });
};
// 用户类型标签选择变化时触发
const handleTagChange = (newSelectedKeys) => {
  // 将选中的标签ID同步到人群表单的userTypes字段
  crowdForm.userTypes = newSelectedKeys;
  console.log('选中的标签ID:', newSelectedKeys);
  // 可选：根据标签数量更新用户数（示例逻辑）
  crowdForm.userNumber = newSelectedKeys.length * 100; // 假设每个标签对应100人
};
// 用户类型操作
// const removeUserType = (type) => {
//   crowdForm.userTypes = crowdForm.userTypes.filter(t => t !== type)
// }
//
// const showInput = () => {
//   inputVisible.value = true
//   nextTick(() => {
//     typeInput.value.focus()
//   })
// }
//
// const addUserType = () => {
//   if (inputValue.value && !crowdForm.userTypes.includes(inputValue.value)) {
//     crowdForm.userTypes.push(inputValue.value)
//   }
//   inputVisible.value = false
//   inputValue.value = ''
// }
</script>

<style scoped>
.crowd-management-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.header {
  height: 60px;
  padding: 10px 20px;
  background-color: #fff;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 20px;
  line-height: 60px;
}

.add-button {
  margin-top: 10px;
}

.search-card {
  margin-bottom: 10px;
}

.table-card {
  margin-bottom: 20px;
}

.el-tag {
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>
